package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.ReportMemberService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportMemberController {
    @Reference
    private ReportMemberService reportMemberService;
    @RequestMapping("/getMemberReport")
     public Result getMemberReport(){
        //查询折线图x轴所需要的一年时间数据
        List<String> timeList=null;
        ArrayList<Integer> numberList=null;
        HashMap<Object, Object> mumberHashMap= new HashMap<>();
        try {
            String time = DateUtils.parseDate2String(new Date(), "YYYY-MM");
            //取出从当前时间开始过去一年的注册时间
            timeList = reportMemberService.findOneYealTime(time);
            Collections.reverse(timeList);
            System.out.println(timeList);
            numberList = new ArrayList<>();
            for (String string : timeList) {
                //查询折线图y轴每个月时间对应的人数
                int count = reportMemberService.findCountBYTime(string);
                numberList.add(count);
            }
            //将时间和人数封装为前台所需要的json格式 { months:[时间数据],memberCount:[人数数据] }

            mumberHashMap.put("months",timeList);
            mumberHashMap.put("memberCount",numberList);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,mumberHashMap);
    }
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        /**
         * 前台 setmealCount接收格式 [{},{}]
         * setmealNames接收格式{ }
         */
        //查询所有套餐名字
        List<String> names = reportMemberService.getSetmealReport();
        //用来存放套餐名和对应的预约数量的集合
        List<Map<String,Object>> maps = reportMemberService.findNameAndNumber();
        System.out.println(maps);
        //
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("setmealCount",maps);
        hashMap.put("setmealNames",names);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,hashMap);
    }
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        Map map=null;
        try {
            map= reportMemberService.getBusinessReportData();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
      return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
    }
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map dataMap = reportMemberService.getBusinessReportData();
            String filePath = request.getSession().
                    getServletContext().getRealPath("template")
                    +File.separator +"report_template.xlsx";
            /*获取集合数据*/
            String reportData = (String) dataMap.get("reportData");
            Integer todayNewMember = (Integer) dataMap.get("todayNewMember");
            Integer totalMember = (Integer) dataMap.get("totalMember");
            Integer thisWeekNewMember = (Integer) dataMap.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) dataMap.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) dataMap.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) dataMap.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) dataMap.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) dataMap.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) dataMap.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) dataMap.get("thisMonthVisitsNumber");
            List hotSetmeal = (List) dataMap.get("hotSetmeal");
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //获取第一个工作薄
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
            //获取第三行
            XSSFRow row = sheetAt.getRow(2);
            //获取第三行的第六个单元格，开始填写数据
            row.getCell(5).setCellValue(reportData);
            //获取第五行
            XSSFRow row1 = sheetAt.getRow(4);
            //获取第五行的第六个单元格，开始填写数据
            row.getCell(5).setCellValue(todayNewMember);
            //获取第五行的第七个单元格，开始填写数据
            row.getCell(7).setCellValue(totalMember);
            //获取第六行
            XSSFRow row2 = sheetAt.getRow(5);
            //获取第六行的第六个单元格，开始填写数据
            row.getCell(5).setCellValue(thisWeekNewMember);
            //获取第六行的第八个单元格，开始填写数据
            row.getCell(7).setCellValue(thisMonthNewMember);
            //获取第八行
            XSSFRow row3 = sheetAt.getRow(7);
            row3.getCell(5).setCellValue(todayOrderNumber);
            row3.getCell(7).setCellValue(todayVisitsNumber);
            //获取第九行
            XSSFRow row4 = sheetAt.getRow(8);
            row3.getCell(5).setCellValue(thisWeekOrderNumber);
            row3.getCell(7).setCellValue(thisWeekVisitsNumber);
            //获取第十行
            XSSFRow row5 = sheetAt.getRow(9);
            row3.getCell(5).setCellValue(thisMonthOrderNumber);
            row3.getCell(7).setCellValue(thisMonthVisitsNumber);
            //获取第十三行
            int rows =12;
            for (int i = 0; i < hotSetmeal.size(); i++) {
                XSSFRow row6 = sheetAt.getRow(rows);
                Map map = (Map) hotSetmeal.get(i);
                String name = (String) map.get("name");
                long setmeal_count = (long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                String remark = (String) map.get("remark");
                row6.getCell(4).setCellValue(name);
                row6.getCell(5).setCellValue(setmeal_count);
                row6.getCell(6).setCellValue(proportion.doubleValue());
                
                row6.getCell(7).setCellValue(remark);
                rows++;
            }
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//告诉浏览器接收类型

            response.setHeader("content-Disposition","attachment;filename=report.xlsx");//告诉浏览器此文件需要下载
            xssfWorkbook.write(outputStream);//将excel表通过response传到前台
            outputStream.flush();
            outputStream.close();
            xssfWorkbook.close();

//            return new Result(true,"导出文件成功");
      return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,"导出文件失败",null);
        }

    }
}
